import time
import traceback

from ..exception.TestException import TestException
from ..common.ui.PageElement import PageElement, POLL_FREQUENCY
from ..exception.errorcode import ErrorCode

from robot.api import logger


class Combobox(PageElement):
    """
    Fish Combobox
    """

    def setValue(self, value):
        self.wait_element_presence()
        self.wait_combobox_datasource_ready()

        script = "return $(arguments[0]).combobox('option', 'dataSource')"
        datasource = self._execute_script(script, self._get_web_element())

        script = "return $(arguments[0]).combobox('option', 'dataTextField')"
        data_text_field = self._execute_script(script, self._get_web_element())

        script = "return $(arguments[0]).combobox('option', 'dataValueField')"
        data_value_field = self._execute_script(script, self._get_web_element())

        select_value = None
        for data in datasource:
            if (value == data[data_text_field]):
                select_value = data[data_value_field]
                break
        if select_value is None:
            raise TestException.by_error_code(ErrorCode.COMBOBOX_VALUE_NOT_EXIST, value=value)
        script = "$(arguments[0]).combobox(arguments[1],arguments[2])"
        self._execute_script(script, self._get_web_element(), 'value', str(select_value))

        try:
            # 为了有些联动的场景，触发select事件，事件参数data是上面获取到的列表数据
            select_script = "$(arguments[0]).trigger(arguments[1], arguments[2])"
            self._execute_script(select_script, self._get_web_element(), 'combobox:select', data)
        except Exception as e:
            logger.warn("Try to trigger the select event failed!")
            traceback.print_exc()

    def clear(self):
        script = "$(arguments[0]).combobox('clear')"
        self._execute_script(script, self._get_web_element())

    # def __get_all_data__(self):
    #     script = "return $(arguments[0]).combobox('option', 'dataSource')"
    #     dataSource = self._execute_script(script, self._get_web_element())
    #
    #     script = "return $(arguments[0]).combobox('option', 'dataTextField')"
    #     dataTextField = self._execute_script(script, self._get_web_element())
    #
    #     script = "return $(arguments[0]).combobox('option', 'dataValueField')"
    #     dataValueField = self._execute_script(script, self._get_web_element())

    def wait_combobox_datasource_ready(self, timeout=10, poll_frequency=POLL_FREQUENCY, recheck=True):
        """
        检查combobox datasource是否有值了，如果没有，则认为元素没有准备好
        :param timeout:
        :param poll_frequency:
        :param recheck:
        :return:
        """
        if recheck:
            self._ready = False
        count = 0
        max_retry = timeout / poll_frequency
        while not self._ready:
            script = "return $(arguments[0]).combobox('option', 'dataSource')"
            dataSource = self._execute_script(script, self._get_web_element())
            count += 1
            if len(dataSource) != 0:
                self._ready = True
            elif count >= max_retry:
                return False
            time.sleep(poll_frequency)
        return self._ready

    def get_identification(self):
        identification = {'class': ['form-control'],
                          'data-ui-role': ['combobox']}
        return identification
